<template>
  <div class="order-detail-container">
    <div class="header-section">
      <el-page-header
        @back="goBack"
        :title="'返回'"
        :content="'订单详情 #' + orderInfo.orderNo"
      />
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <template v-else>
      <!-- 订单基本信息 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>订单信息</span>
            <el-tag :type="getStatusType(orderInfo.orderStatus)">{{
              orderInfo.statusText
            }}</el-tag>
          </div>
        </template>
        <div class="order-info">
          <div class="info-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ orderInfo.orderNo }}</span>
          </div>
          <div class="info-item">
            <span class="label">下单时间：</span>
            <span class="value">{{ orderInfo.createdAt }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付方式：</span>
            <span class="value">{{
              getPaymentMethodText(orderInfo.paymentMethod)
            }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付时间：</span>
            <span class="value">{{ orderInfo.paymentTime || "未支付" }}</span>
          </div>
          <div class="info-item">
            <span class="label">订单备注：</span>
            <span class="value">{{ orderInfo.remark || "无" }}</span>
          </div>
        </div>
      </el-card>

      <!-- 收货信息 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>收货信息</span>
          </div>
        </template>
        <div class="address-info" v-if="orderInfo.address">
          <div class="info-item">
            <span class="label">收货人：</span>
            <span class="value">{{ orderInfo.address.recipientName }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系电话：</span>
            <span class="value">{{ orderInfo.address.recipientPhone }}</span>
          </div>
          <div class="info-item">
            <span class="label">收货地址：</span>
            <span class="value">{{ formatAddress(orderInfo.address) }}</span>
          </div>
        </div>
        <div v-else>暂无收货信息</div>
      </el-card>

      <!-- 商品信息 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>商品信息</span>
          </div>
        </template>
        <el-table :data="orderInfo.items || []" style="width: 100%" border>
          <el-table-column label="商品图片" width="100">
            <template #default="scope">
              <el-image
                style="width: 60px; height: 60px"
                :src="scope.row.product ? scope.row.product.image : ''"
                fit="cover"
                :preview-src-list="
                  scope.row.product ? [scope.row.product.image] : []
                "
              >
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="商品名称">
            <template #default="scope">
              {{
                scope.row.product
                  ? scope.row.product.name
                  : scope.row.productName
              }}
            </template>
          </el-table-column>
          <el-table-column label="规格" width="150">
            <template #default="scope">
              {{ scope.row.sku ? scope.row.sku.specs : "" }}
            </template>
          </el-table-column>
          <el-table-column label="单价" width="100">
            <template #default="scope">
              ¥{{ scope.row.sku ? scope.row.sku.price : scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column label="小计" width="120">
            <template #default="scope"> ¥{{ scope.row.subtotal }} </template>
          </el-table-column>
        </el-table>

        <div class="order-summary">
          <div class="summary-row">
            <span class="label">商品小计：</span>
            <span class="value">¥{{ orderInfo.goodsAmount }}</span>
          </div>
          <div class="summary-row">
            <span class="label">运费：</span>
            <span class="value">¥{{ orderInfo.deliveryFee }}</span>
          </div>
          <div class="summary-row" v-if="orderInfo.discountAmount > 0">
            <span class="label">优惠：</span>
            <span class="value discount">-¥{{ orderInfo.discountAmount }}</span>
          </div>
          <div class="summary-row total">
            <span class="label">订单总计：</span>
            <span class="value price">¥{{ orderInfo.totalAmount }}</span>
          </div>
        </div>
      </el-card>

      <!-- 金额信息 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>金额信息</span>
          </div>
        </template>
        <div class="amount-info">
          <div class="info-item">
            <span class="label">商品总额：</span>
            <span class="value">¥{{ orderInfo.goodsAmount }}</span>
          </div>
          <div class="info-item">
            <span class="label">配送费用：</span>
            <span class="value">¥{{ orderInfo.deliveryFee }}</span>
          </div>
          <div class="info-item">
            <span class="label">优惠金额：</span>
            <span class="value">-¥{{ orderInfo.discountAmount }}</span>
          </div>
          <div class="info-item total">
            <span class="label">实付金额：</span>
            <span class="value price">¥{{ orderInfo.totalAmount }}</span>
          </div>
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button
          v-if="
            orderInfo.payStatus === 1 &&
            (orderInfo.orderStatus < 2 || orderInfo.status === 'paid') &&
            orderInfo.deliveryType === 'local'
          "
          type="primary"
          @click="handleReadyForDelivery"
          >备货完成</el-button
        >
        <el-button
          v-if="orderInfo.payStatus === 0"
          type="danger"
          @click="handleCancelOrder"
          >取消订单</el-button
        >
        <el-button
          v-if="
            orderInfo.payStatus === 1 &&
            orderInfo.deliveryType === 'self' &&
            (orderInfo.orderStatus < 2 || orderInfo.status === 'paid')
          "
          type="success"
          @click="handleReadyForPickup"
          >确认自提准备完成</el-button
        >
        <el-button
          v-if="
            orderInfo.payStatus === 1 &&
            orderInfo.orderStatus === 3 &&
            orderInfo.deliveryType === 'local' &&
            (!orderInfo.delivery ||
              !orderInfo.delivery.riderId ||
              orderInfo.delivery.riderId === -1)
          "
          type="warning"
          @click="openAssignRiderDialog"
          >手动分配骑手</el-button
        >
      </div>
    </template>

    <!-- 配送方式对话框 -->
    <el-dialog title="配送方式选择" v-model="shipDialogVisible" width="500px">
      <el-form
        :model="shipForm"
        label-width="100px"
        ref="shipFormRef"
        :rules="shipRules"
      >
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="shipForm.orderNo" disabled />
        </el-form-item>
        <el-form-item label="配送方式" prop="deliveryType">
          <el-radio-group v-model="shipForm.deliveryType">
            <el-radio label="local">同城配送</el-radio>
            <el-radio label="self">自提</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip" :loading="shipLoading"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 分配骑手对话框 -->
    <el-dialog
      title="分配骑手"
      v-model="assignRiderDialogVisible"
      width="500px"
    >
      <el-form
        :model="assignRiderForm"
        label-width="100px"
        ref="assignRiderFormRef"
        :rules="assignRiderRules"
      >
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="assignRiderForm.orderNo" disabled />
        </el-form-item>
        <el-form-item label="选择骑手" prop="riderId">
          <el-select
            v-model="assignRiderForm.riderId"
            placeholder="请选择骑手"
            filterable
            :loading="ridersLoading"
          >
            <el-option
              v-for="rider in availableRiders"
              :key="rider.id"
              :label="`${rider.name} (${rider.phone}) - 当前${rider.currentOrderCount}单`"
              :value="rider.id"
            >
              <div class="rider-option">
                <span>{{ rider.name }}</span>
                <span class="rider-phone">{{ rider.phone }}</span>
                <el-tag
                  size="small"
                  :type="rider.status === 1 ? 'success' : 'warning'"
                >
                  {{ rider.status === 1 ? "空闲" : "忙碌" }} ({{
                    rider.currentOrderCount
                  }}单)
                </el-tag>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignRiderDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmAssignRider"
            :loading="assignRiderLoading"
            >确认分配</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getOrderDetail,
  confirmReadyForPickup,
  assignRider,
  confirmLocalOrderReady,
  manualAssignRider,
} from "@/api/orders";
import { getAvailableRiders2 } from "@/api/riders";

const route = useRoute();
const router = useRouter();
const loading = ref(true);
const orderInfo = ref({});

// 配送方式相关
const shipDialogVisible = ref(false);
const shipLoading = ref(false);
const shipFormRef = ref(null);

const shipForm = reactive({
  orderId: null,
  orderNo: "",
  deliveryType: "local",
});

const shipRules = {
  deliveryType: [
    { required: true, message: "请选择配送方式", trigger: "change" },
  ],
};

// 分配骑手相关
const assignRiderDialogVisible = ref(false);
const assignRiderLoading = ref(false);
const assignRiderFormRef = ref(null);
const ridersLoading = ref(false);
const availableRiders = ref([]);

const assignRiderForm = reactive({
  orderNo: "",
  riderId: null,
});

const assignRiderRules = {
  riderId: [{ required: true, message: "请选择骑手", trigger: "change" }],
};

// 获取订单详情
const fetchOrderDetail = async () => {
  const orderId = route.params.id;
  if (!orderId) {
    ElMessage.error("订单ID不能为空");
    return;
  }

  loading.value = true;
  try {
    const res = await getOrderDetail(orderId);
    if (res.code === 200) {
      orderInfo.value = res.data;
      // 设置状态文本
      orderInfo.value.statusText = getStatusText(
        orderInfo.value.orderStatus,
        orderInfo.value.payStatus
      );
    } else {
      ElMessage.error(res.msg || "获取订单详情失败");
    }
  } catch (error) {
    console.error("获取订单详情失败:", error);
    ElMessage.error("获取订单详情失败");
  } finally {
    loading.value = false;
  }
};

// 获取订单状态文本
const getStatusText = (orderStatus, payStatus) => {
  if (payStatus === 0) return "待付款";
  if (payStatus === 2) return "已退款";

  // 处理数字类型的orderStatus
  if (typeof orderStatus === "number") {
    switch (orderStatus) {
      case 0:
        return "待处理";
      case 1:
        return "备货中";
      case 2:
        return "打包中";
      case 3:
        return "配送中";
      case 4:
        return "已完成";
      case 5:
        return "已取消";
      case 6:
        return "待确认收货";
      default:
        return "未知状态";
    }
  }

  // 处理字符串类型的status
  if (typeof orderStatus === "string") {
    switch (orderStatus) {
      case "pending":
        return "待付款";
      case "paid":
        return "备货中";
      case "packaging":
        return "打包中";
      case "shipping":
        return "配送中";
      case "completed":
        return "已完成";
      case "cancelled":
        return "已取消";
      default:
        return orderStatus;
    }
  }

  return "未知状态";
};

// 获取订单状态类型
const getStatusType = (status) => {
  // 处理数字类型的状态
  if (typeof status === "number") {
    const statusMap = {
      0: "warning", // 待处理
      1: "info", // 备货中
      2: "primary", // 打包中
      3: "success", // 配送中
      4: "success", // 已完成
      5: "info", // 已取消
      6: "success", // 待确认收货
    };
    return statusMap[status] || "info";
  }

  // 处理字符串类型的状态
  const statusMap = {
    pending: "warning",
    paid: "info",
    packaging: "primary",
    shipping: "success",
    completed: "success",
    cancelled: "info",
  };
  return statusMap[status] || "info";
};

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const methodMap = {
    wechat: "微信支付",
    alipay: "支付宝",
    balance: "余额支付",
  };
  return methodMap[method] || method;
};

// 格式化地址
const formatAddress = (address) => {
  if (!address) return "";
  return `${address.province}${address.city}${address.district}${address.detailAddress}`;
};

// 返回上一页
const goBack = () => {
  // 检查是否从首页来的
  if (route.query.source === "dashboard") {
    router.push("/home/index");
  } else {
    router.push("/home/orders");
  }
};

// 处理备货完成
const handleReadyForDelivery = () => {
  ElMessageBox.confirm(
    "确认该订单商品已备货完成？点击确认后将自动分配骑手进行配送。",
    "确认操作",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        const res = await confirmLocalOrderReady(orderInfo.value.id);
        if (res.code === 200) {
          ElMessage.success("操作成功，订单已准备完成并分配骑手进行配送");
          fetchOrderDetail(); // 刷新订单详情
        } else {
          ElMessage.error(res.msg || "操作失败");
        }
      } catch (error) {
        console.error("确认订单准备完成失败:", error);
        ElMessage.error("操作失败");
      }
    })
    .catch(() => {});
};

// 取消订单
const handleCancelOrder = () => {
  ElMessageBox.confirm("确认取消该订单吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage.success("订单已取消");
      fetchOrderDetail(); // 刷新订单详情
    })
    .catch(() => {});
};

// 处理确认自提订单准备完成
const handleReadyForPickup = () => {
  ElMessageBox.confirm(
    "确认该自提订单商品已准备完成，可以通知用户前来取货？",
    "确认操作",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        const res = await confirmReadyForPickup(orderInfo.value.id);
        if (res.code === 200) {
          ElMessage.success("操作成功，已通知用户可以前来取货");
          fetchOrderDetail(); // 刷新订单详情
        } else {
          ElMessage.error(res.msg || "操作失败");
        }
      } catch (error) {
        console.error("确认自提准备完成失败:", error);
        ElMessage.error("操作失败");
      }
    })
    .catch(() => {});
};

// 确认发货
const confirmShip = async () => {
  if (!shipFormRef.value) return;

  await shipFormRef.value.validate(async (valid) => {
    if (!valid) return;

    shipLoading.value = true;
    try {
      let res;
      if (shipForm.deliveryType === "self") {
        res = await confirmReadyForPickup(shipForm.orderId);
      } else {
        res = await confirmLocalOrderReady(shipForm.orderId);
      }

      if (res.code === 200) {
        ElMessage.success("操作成功");
        shipDialogVisible.value = false;
        fetchOrderDetail(); // 刷新订单详情
      } else {
        ElMessage.error(res.msg || "操作失败");
      }
    } catch (error) {
      console.error("操作失败:", error);
      ElMessage.error("操作失败");
    } finally {
      shipLoading.value = false;
    }
  });
};

// 打开分配骑手对话框
const openAssignRiderDialog = async () => {
  assignRiderForm.orderNo = orderInfo.value.orderNo;
  assignRiderForm.riderId = null;

  // 获取可用骑手列表
  ridersLoading.value = true;
  try {
    const res = await getAvailableRiders2();
    if (res.code === 200) {
      availableRiders.value = res.data;
    } else {
      ElMessage.error(res.msg || "获取可用骑手列表失败");
    }
  } catch (error) {
    console.error("获取可用骑手列表失败:", error);
    ElMessage.error("获取可用骑手列表失败");
  } finally {
    ridersLoading.value = false;
  }

  assignRiderDialogVisible.value = true;
};

// 确认分配骑手
const confirmAssignRider = async () => {
  if (!assignRiderFormRef.value) return;

  await assignRiderFormRef.value.validate(async (valid) => {
    if (!valid) return;

    assignRiderLoading.value = true;
    try {
      const res = await manualAssignRider(
        orderInfo.value.id,
        assignRiderForm.riderId
      );
      if (res.code === 200) {
        ElMessage.success("骑手分配成功");
        assignRiderDialogVisible.value = false;
        fetchOrderDetail(); // 刷新订单详情
      } else {
        ElMessage.error(res.msg || "骑手分配失败");
      }
    } catch (error) {
      console.error("骑手分配失败:", error);
      ElMessage.error("骑手分配失败");
    } finally {
      assignRiderLoading.value = false;
    }
  });
};

onMounted(() => {
  fetchOrderDetail();
});
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
}

.header-section {
  margin-bottom: 20px;
}

.loading-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
}

.label {
  width: 100px;
  color: #606266;
}

.value {
  flex: 1;
  color: #303133;
}

.total {
  margin-top: 20px;
  font-weight: bold;
}

.price {
  color: #f56c6c;
  font-size: 18px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.order-summary {
  margin-top: 20px;
  padding: 15px 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #eee;
}

.summary-row {
  display: flex;
  justify-content: flex-end;
  margin: 5px 0;
  font-size: 14px;
}

.summary-row .label {
  color: #606266;
  margin-right: 15px;
}

.summary-row .value {
  color: #333;
  min-width: 80px;
  text-align: right;
}

.summary-row .discount {
  color: #67c23a;
}

.summary-row.total {
  margin-top: 10px;
  font-weight: bold;
  border-top: 1px dashed #ddd;
  padding-top: 10px;
}

.summary-row.total .value {
  color: #ff6700;
  font-size: 16px;
}

/* 骑手选项样式 */
.rider-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.rider-phone {
  margin: 0 10px;
  color: #909399;
}
</style> 